package jsu.lipengcheng.trafficnet.common;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import jsu.lipengcheng.trafficnet.pojo.Ticket;
import jsu.lipengcheng.trafficnet.pojo.TicketImportDTO;
import jsu.lipengcheng.trafficnet.service.TicketService;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class TicketDataListener extends AnalysisEventListener<TicketImportDTO> {

    private final TicketService ticketService;
    private List<Ticket> tickets = new ArrayList<>();

    public TicketDataListener(TicketService ticketService) {
        this.ticketService = ticketService;
    }

    // 每读取一行数据都会执行这个方法
    @Override
    public void invoke(TicketImportDTO data, AnalysisContext context) {
        Ticket ticket = new Ticket();
        BeanUtils.copyProperties(data,ticket); // 建议手动赋值更安全
        tickets.add(ticket);

        // 批量插入优化
        if (tickets.size() >= 500) {
            ticketService.saveBatch(tickets);
            tickets.clear();
        }
    }

    // 所有数据解析完成之后会执行这个方法
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!tickets.isEmpty()) {
            ticketService.saveBatch(tickets);
        }
    }
}
